package com.dhl.fin.api.service;

import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.dhl.fin.api.common.util.MapUtil;
import com.dhl.fin.api.common.util.SpringContextUtil;
import com.dhl.fin.api.config.AliOssConfig;
import com.dhl.fin.api.constant.WebConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;

/**
 * 阿里云OSS对象存储服务
 */
@Slf4j
@Service
public class OSSServiceImpl {

    @Autowired
    AliOssConfig aliOssConfig;


    public void uploadToAliOss(String fileName, Workbook workbook) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        workbook.write(outputStream);
        uploadToAliOss(fileName, null, new ByteArrayInputStream(outputStream.toByteArray()));
    }

    /**
     * 上传文件到OSS上，并返回文件的URL地址
     *
     * @param fileName
     * @param subPath
     * @param fileInputStream
     * @return
     */
    public String uploadToAliOss(String fileName, String subPath, InputStream fileInputStream) {
        AliOssConfig aliOssConfig = SpringContextUtil.getBean(AliOssConfig.class);
        OSS ossClient = new OSSClientBuilder().build(aliOssConfig.getEndPoint(), aliOssConfig.getAccessKeyId(), aliOssConfig.getAccessKeySecret());
        subPath = subPath.replaceAll("\\\\", "/");
        fileName = fileName.replaceAll(" ", "");
        String objectName = StrUtil.isNotEmpty(subPath) ? subPath + "/" + fileName : aliOssConfig.getFilePath() + fileName;
        String fileUrl = StrUtil.concat(true, "https://",
                aliOssConfig.getBucketName(), ".",
                aliOssConfig.getEndPoint(),
                "/",
                objectName);

        try {
            ossClient.putObject(aliOssConfig.getBucketName(), objectName, fileInputStream);
            return fileUrl;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("上传文件到OSS失败：" + e.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }

    /**
     * @param fileUrl 文件的url地址
     * @return
     * @throws MalformedURLException
     */
    public InputStream getFileInputStreamFromAliOss(String fileUrl) throws MalformedURLException {
        OSS ossClient = new OSSClientBuilder().build(aliOssConfig.getEndPoint(), aliOssConfig.getAccessKeyId(), aliOssConfig.getAccessKeySecret());
        Map headers = MapUtil.builder().add(WebConstant.CONTENT_DISPOSITION, "attachment").build();
        OSSObject ossObject = ossClient.getObject(new URL(fileUrl), headers);
        return ossObject.getObjectContent();
    }

}


